package org.lanqiao.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

/**
 * 编码过滤器（只能解决post方式）
 * @author WZW
 *
 */
@WebFilter(
		description = "这是一个编码过滤器", 
		urlPatterns = { "/*" }, 
		initParams = { 
				@WebInitParam(name = "charset", value = "utf-8", description = "设置的编码格式")
		}
		)
public class CharsetEncodingFilter implements Filter{

	private String global_charset="iso8859-1";
	
	@Override
	//卸载
	public void destroy() {
		
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		request.setCharacterEncoding(global_charset);
		response.setCharacterEncoding(global_charset);
		chain.doFilter(request, response);
		
	}

	/**
	 * 从web.xml中获得  全局变量的config    ，从未进行初始化
	 */
	@Override
	public void init(FilterConfig config) throws ServletException 
	{
		String charset=config.getInitParameter("charset");
		
		if(charset!=null&&charset!="") {
			this.global_charset= charset;
		}
	}
	
}
